package com.cypher.encryptionanddecryption.fragment.protocol.nb25;

import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.Nb25ProtocolUtils;

import org.apache.commons.lang3.StringUtils;

/**
 * 采集服务参数页面
 * @author: 古霸天
 * @date: 2020/12/14
 */
public class CollectionServiceParamFragment extends AbstractProtocolFragment {
    private final String EMPTY = "";
    /**
     * 服务器地址入框
     */
    private EditText serviceAddressTxt;
    /**
     * 端口号输入框
     */
    private EditText portTxt;
    private Button chinaUnicornBtn;
    private Button chinaMobileBtn;
    private CommunicationBean bean;
    private BluetoothCommunicationActivity activity;
    private Handler handler;
    public CollectionServiceParamFragment(BluetoothCommunicationActivity activity, CommunicationBean bean) {
        this.activity = activity;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_nb25_collection_service_param, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    /**
     * 初始化
     * @param v
     */
    private void init(View v) {
        handler = new Handler();

        serviceAddressTxt = v.findViewById(R.id.service_address);

        portTxt = v.findViewById(R.id.port);
        portTxt.setInputType(InputType.TYPE_CLASS_NUMBER);

        chinaUnicornBtn = v.findViewById(R.id.china_unicorn_address_btn);
        chinaMobileBtn = v.findViewById(R.id.china_mobile_address_btn);

        chinaUnicornBtn.setOnClickListener((view) -> {
            serviceAddressTxt.setText("124.70.66.214");
            portTxt.setText("5683");
        });
        chinaMobileBtn.setOnClickListener((view) -> {
            serviceAddressTxt.setText("117.60.157.137");
            portTxt.setText("5683");
        });
    }

    @Override
    public void fillFragment(String data) {
        // 清空内容
        serviceAddressTxt.setText("");
        portTxt.setText("");

        Runnable r = () -> {
            reader(Nb25ProtocolUtils.formatReceiveData(data));
        };
        handler.postDelayed(r, 200);

    }
    @Override
    public String getHexCode(String rwType) {
        if (StringUtils.equals("read", rwType)) {
            return Nb25ProtocolUtils.getReadCommand(bean.getHexCode(), PROTOCOL_VERSION);
        }
        // 组包
        return getData();
    }

    /**
     * 渲染页面
     * @param data
     */
    private void reader(String data) {
        String ip = data.substring(0, 32);
        int index = ip.indexOf("00");
        if (index > 0) {
            ip = ip.substring(0, index);
        }
        String[] ips = ip.split("2E");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < ips.length; i++) {
            buf.append(HexUtils.ascToStr(ips[i]));
            if (i != ips.length - 1) {
                buf.append(".");
            }
        }
        serviceAddressTxt.setText(buf.toString());
        portTxt.setText(String.valueOf(Integer.parseInt(data.substring(32, 36), 16)));

    }
    /**
     * 获取数据域
     * @return
     */
    private String getData() {
        String serviceAddress = serviceAddressTxt.getText().toString();
        if (StringUtils.isEmpty(serviceAddress)) {
            Toast.makeText(activity, "服务器地址不能为空", Toast.LENGTH_SHORT).show();
            return EMPTY;
        }
        String port = portTxt.getText().toString();
        if (StringUtils.isEmpty(port)) {
            Toast.makeText(activity, "端口号不能为空", Toast.LENGTH_SHORT).show();
            return EMPTY;
        }

        //小数点分割需要转义
        String[] addresses = serviceAddress.split("\\.");
        if (addresses.length != 4) {
            Toast.makeText(activity, "输入的IP地址错误, 请检查", Toast.LENGTH_SHORT).show();
            return EMPTY;
        }

        StringBuffer addressBuf = new StringBuffer();
        for (int i = 0; i < addresses.length; i++) {
            String address = addresses[i];
            if (StringUtils.isEmpty(address) || Integer.parseInt(address) > 255) {
                Toast.makeText(activity, "输入的IP地址错误, 请检查", Toast.LENGTH_SHORT).show();
                return EMPTY;
            }
            addressBuf.append(HexUtils.strToAsc(address));
            if (i != addresses.length -1) addressBuf.append("2E");
        }
        StringBuffer data = new StringBuffer();
        data.append(HexUtils.paddingRight(addressBuf.toString(), 32));
        data.append(HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(port)), 4));
        return Nb25ProtocolUtils.getWriteCommand(bean.getHexCode(), data.toString(), PROTOCOL_VERSION);
    }
}
